<template>
  <div class="dashboard-container">
    <!-- 欢迎标语 -->
    <div class="welcome-banner">
      <div class="welcome-content">
        <h1>智慧养老管理系统</h1>
        <p class="slogan">关爱老人，从心开始</p>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总子女数</span>
              <el-icon>
                <User/>
              </el-icon>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ childCount }}</div>
            <div class="card-footer">关爱老人的子女数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总老人数</span>
              <el-icon>
                <UserFilled/>
              </el-icon>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ elderCount }}</div>
            <div class="card-footer">享受服务的老人数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总医生数</span>
              <el-icon>
                <UserFilled/>
              </el-icon>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ doctorCount }}</div>
            <div class="card-footer">专业医疗团队数量</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总社区数</span>
              <el-icon>
                <House/>
              </el-icon>
            </div>
          </template>
          <div class="card-content">
            <div class="number">{{ communityCount }}</div>
            <div class="card-footer">服务覆盖社区数量</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>各社区老人分布</span>
              <div class="chart-subtitle">了解各社区服务情况</div>
            </div>
          </template>
          <div class="chart-content">
            <div ref="elderChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>检查任务完成情况</span>
              <div class="chart-subtitle">跟踪健康检查进度</div>
            </div>
          </template>
          <div class="chart-content">
            <div ref="taskChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动列表 -->
    <el-card class="activity-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>最近活动</span>
            <div class="chart-subtitle">了解最新社区动态</div>
          </div>
          <el-button type="primary" @click="viewAllActivities">查看全部</el-button>
        </div>
      </template>
      <el-table :data="recentActivities" style="width: 100%" :stripe="true" :border="true">
        <el-table-column prop="actionName" label="活动名称" min-width="150"/>
        <el-table-column prop="actionContext" label="活动内容" show-overflow-tooltip min-width="300"/>
        <el-table-column prop="actionTime" label="活动时间" width="180"/>
        <el-table-column prop="community.name" label="所属社区" min-width="120"/>
      </el-table>
    </el-card>

    <!-- 底部标语 -->
    <div class="footer-slogan">
      <p>让每一位老人都能安享幸福晚年</p>
      <p>用科技守护健康，让关爱无处不在</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, onActivated} from 'vue'
import {useRouter} from 'vue-router'
import {User, UserFilled, House} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '@/utils/request'
import type {Action} from '@/types/community'
import {findAllChild} from '@/api/child'
import {getAllElders} from '@/api/elder'
import {getAllDoctors} from '@/api/doctor'
import {getAllCommunities} from '@/api/community'

const router = useRouter()
const childCount = ref(0)
const elderCount = ref(0)
const doctorCount = ref(0)
const communityCount = ref(0)
const recentActivities = ref<Action[]>([])
const elderChart = ref<HTMLElement>()
const taskChart = ref<HTMLElement>()

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const [children, elders, doctors, communities] = await Promise.all([
      findAllChild(),
      getAllElders(),
      getAllDoctors(),
      getAllCommunities()
    ])
    childCount.value = children.length
    elderCount.value = elders.length
    doctorCount.value = doctors.length
    communityCount.value = communities.length
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取社区老人分布数据
const fetchElderDistribution = async () => {
  try {
    const [communities, elders] = await Promise.all([
      getAllCommunities(),
      getAllElders()
    ])

    // 统计每个社区的老人数量
    const distribution = communities.map(community => ({
      name: community.name,
      value: elders.filter(elder => elder.communityId === community.id).length
    }))

    const chart = echarts.init(elderChart.value!)
    chart.setOption({
      title: {
        text: '各社区老人分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: distribution,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  } catch (error) {
    console.error('获取老人分布数据失败:', error)
    // 显示空数据图表
    const chart = echarts.init(elderChart.value!)
    chart.setOption({
      title: {
        text: '各社区老人分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: [{name: '暂无数据', value: 1}],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }
}

const fetchTaskCompletion = async () => {
  try {
    const tasks = await request.get('/admin/getAllCheckTask')

    // 1. 过滤无效数据
    const validTasks = tasks.filter(task =>
        task.date && (task.finish === true || task.finish === false)
    )

    // 2. 按日期分组统计
    const completionData = validTasks.reduce((acc: any, task: any) => {
      const date = task.date
      if (!acc[date]) {
        acc[date] = {completed: 0, uncompleted: 0}
      }
      task.finish ? acc[date].completed++ : acc[date].uncompleted++
      return acc
    }, {})

    // 3. 按日期排序
    const dates = Object.keys(completionData).sort()
    const completed = dates.map(date => completionData[date].completed)
    const uncompleted = dates.map(date => completionData[date].uncompleted)

    // 4. 渲染图表
    const chart = echarts.init(taskChart.value!)
    chart.setOption({
      title: {
        text: '检查任务完成情况',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          let result = params[0].axisValue + '<br/>'
          params.forEach((param: any) => {
            result += `${param.marker} ${param.seriesName}: ${param.value}<br/>`
          })
          return result
        }
      },
      legend: {
        data: ['已完成', '未完成'],
        bottom: 0
      },
      xAxis: {
        type: 'category',
        data: dates.length > 0 ? dates : ['暂无数据']
      },
      yAxis: {
        type: 'value',
        name: '任务数量',
        minInterval: 1
      },
      series: [
        {
          name: '已完成',
          type: 'line',
          data: completed,
          smooth: true,
          itemStyle: {color: '#67C23A'}
        },
        {
          name: '未完成',
          type: 'line',
          data: uncompleted,
          smooth: true,
          itemStyle: {color: '#F56C6C'}
        }
      ]
    })
  } catch (error) {
    console.error('获取任务完成情况失败:', error)
    // 显示空数据图表
    const chart = echarts.init(taskChart.value!)
    chart.setOption({
      xAxis: {type: 'category', data: ['暂无数据']},
      yAxis: {type: 'value', name: '任务数量'},
      series: [
        {name: '已完成', type: 'line', data: [0]},
        {name: '未完成', type: 'line', data: [0]}
      ]
    })
  }
}

// 获取最近活动
const fetchRecentActivities = async () => {
  try {
    const [activities, communities] = await Promise.all([
      request.get('/admin/getAllAction'),
      getAllCommunities()
    ])

    // 按时间排序并只显示最近5条活动，同时添加社区名称
    recentActivities.value = activities
        .sort((a: Action, b: Action) => new Date(b.actionTime).getTime() - new Date(a.actionTime).getTime())
        .slice(0, 5)
        .map(activity => ({
          ...activity,
          community: communities.find(c => c.id === activity.communityId) || {name: '未知社区'}
        }))
  } catch (error) {
    console.error('获取最近活动失败:', error)
  }
}

// 查看全部活动
const viewAllActivities = () => {
  router.push('/community')
}

function getData() {
  fetchStatistics()
  fetchElderDistribution()
  fetchTaskCompletion()
  fetchRecentActivities()
}

onActivated(() => {
  getData()
})

</script>

<style scoped>
.dashboard-container {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.welcome-banner {
  background: linear-gradient(135deg, #409EFF 0%, #2c3e50 100%);
  color: white;
  padding: 40px;
  border-radius: 12px;
  margin-bottom: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.welcome-banner h1 {
  font-size: 32px;
  font-weight: 600;
  margin: 0 0 15px;
}

.welcome-banner p {
  margin: 0;
  font-size: 18px;
  opacity: 0.9;
}

.stat-row {
  margin-bottom: 40px;
}

.stat-card {
  transition: all 0.3s;
  border: none;
  height: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.card-content {
  text-align: center;
  padding: 20px;
}

.number {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.card-footer {
  color: #909399;
  font-size: 14px;
}

.chart-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.chart-card:hover {
  transform: translateY(-5px);
}

.chart-card h3 {
  margin: 0 0 24px 0;
  font-size: 20px;
  color: #303133;
  font-weight: 500;
}

.chart {
  height: 350px;
}

.activity-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-top: 40px;
  margin-bottom: 40px;
  transition: all 0.3s;
}

.activity-card:hover {
  transform: translateY(-5px);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.header-left span {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.chart-subtitle {
  font-size: 14px;
  color: #909399;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Dialog styles */
:deep(.el-dialog__header) {
  margin: 0;
  padding: 24px 30px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 24px 30px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dialog__footer) {
  padding: 24px 30px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.footer-slogan {
  text-align: center;
  padding: 40px;
  color: #ffffff;
  font-size: 20px;
  font-weight: 400;
  line-height: 1.8;
  background: linear-gradient(135deg, #409EFF 0%, #2c3e50 100%);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.footer-slogan p {
  margin: 8px 0;
}
</style> 